<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Merchmanagement extends Controller_Admin_Template {

	const INDEX_PAGE = 'admin/merchmanagement/';
	
	public function before() {
		parent::before();
		
		$this->template->title = __('Merchandise Management');
	}

	public function action_index() {
		$categories = ORM::factory('category')
		->where('parent_category_id', '=', 0)
		->order_by('name', 'asc')
		->find_all();

		$view = new View('admin/merchmanagement/index');
		$view->set("categories", $categories);
		$this->template->title = __('Merchandise Management');
		$this->template->content = $view;
	}
	
	/*
	public function action_new() {
		$category = new Model_Category();

		$root_categories = ORM::factory('category')
		->where('parent_category_id', '=', 0)
		->find_all()->as_array('id', 'name');

		$view = new View('admin/merchamanagement/categories/edit');
		$view->set('category', $category);
		$view->set('root_categories', $root_categories);

		$this->template->content = $view;
	}*/

	public function action_delete() {
		$category_id = $this->request->param('id');
		$category = new Model_Category($category_id);
		$subcategories = $category->subcategories->find_all();

		foreach($subcategories as $subcategory):
		$subcategory->delete();
		endforeach;

		$category->delete();
		$this->request->redirect(self::INDEX_PAGE);
	}

	public function action_save() {
		$category_id = $this->request->param('id')	;
		$category = new Model_Category($category_id);
		$category->values($_POST);
		$category->save();

		$this->request->redirect(self::INDEX_PAGE);
	}

	public function action_attributes() {
		$category_id = $this->request->param('id');
		$category = new Model_Category($category_id);

		$attributes = $category->attributes->find_all();

		$view = new View('admin/merchmanagement/attributes/index');
		$view->set('category', $category);
		$view->set('attributes', $attributes);
		$this->template->content = $view;

	}

	public function action_add() {
		$parent_category_id = $this->request->param('id');
		$category = new Model_Category();
		$category->values($_POST);
		$category->parent_category_id = $parent_category_id;

		$category->save();
		$this->request->redirect(self::INDEX_PAGE);
	}
}